package com.ruoyi.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.service.CommonService;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.domain.SysNoticeSend;
import com.ruoyi.system.domain.bo.SysNoticeBo;
import com.ruoyi.system.domain.vo.SysNoticeVo;
import com.ruoyi.system.service.ISysNoticeSendService;
import com.ruoyi.system.service.ISysNoticeService;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 通知公告
 *
 * @author ruoyi
 * @date 2024-10-23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController {

    private final ISysNoticeService iSysNoticeService;
    private final CommonService commonService;
    private final ISysNoticeSendService noticeSendService;

    /**
     * 查询通知公告列表
     */
    @SaCheckPermission("system:notice:list")
    @GetMapping("/list")
    public TableDataInfo<SysNoticeVo> list(SysNoticeBo bo, PageQuery pageQuery) {
        return iSysNoticeService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出通知公告列表
     */
    @SaCheckPermission("system:notice:export")
    @Log(title = "通知公告", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysNoticeBo bo, HttpServletResponse response) {
        List<SysNoticeVo> list = iSysNoticeService.queryList(bo);
        ExcelUtil.exportExcel(list, "通知公告", SysNoticeVo.class, response);
    }

    /**
     * 获取通知公告详细信息
     *
     * @param noticeId 主键
     */
    @SaCheckPermission("system:notice:query")
    @GetMapping("/{noticeId}")
    public R<SysNoticeVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long noticeId) {
        return R.ok(iSysNoticeService.queryById(noticeId));
    }

    /**
     * 新增通知公告
     */
    @SaCheckPermission("system:notice:add")
    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysNoticeBo bo) {
        return toAjax(iSysNoticeService.insertByBo(bo));
    }

    /**
     * 修改通知公告
     */
    @SaCheckPermission("system:notice:edit")
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysNoticeBo bo) {
        return toAjax(iSysNoticeService.updateByBo(bo));
    }

    /**
     * 删除通知公告
     *
     * @param noticeIds 主键串
     */
    @SaCheckPermission("system:notice:remove")
    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @DeleteMapping("/{noticeIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] noticeIds) {
        return toAjax(iSysNoticeService.deleteWithValidByIds(Arrays.asList(noticeIds), true));
    }


    /**
     * 补充用户数据，并返回系统消息
     * @return
     */
    @Log(title = "系统消息")
    @GetMapping("/listByUser")
    public R<Map<String, Object>> listByUser(@RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        LoginUser loginUser = commonService.getLoginUser();
        Long userId = loginUser.getUserId();
        // 1.将系统消息补充到用户通告阅读标记表中
        LambdaQueryWrapper<SysNotice> querySaWrapper = new LambdaQueryWrapper<SysNotice>();
        querySaWrapper.eq(SysNotice::getMsgType, Constants.MSG_TYPE_ALL); // 全部人员
        querySaWrapper.eq(SysNotice::getStatus,Constants.CLOSE_FLAG_0.toString());  // 未关闭
        querySaWrapper.eq(SysNotice::getSendStatus, Constants.HAS_SEND); //已发布
        //querySaWrapper.ge(SysNotice::getEndTime, loginUser.getCreateTime()); //新注册用户不看结束通知
        querySaWrapper.notInSql(SysNotice::getNoticeId,"select notice_id from sys_notice_send where user_id='"+userId+"'");
        List<SysNotice> notices = iSysNoticeService.list(querySaWrapper);
        if(notices.size()>0) {
            for(int i=0;i<notices.size();i++) {
                //因为websocket没有判断是否存在这个用户，要是判断会出现问题，故在此判断逻辑
                LambdaQueryWrapper<SysNoticeSend> query = new LambdaQueryWrapper<>();
                query.eq(SysNoticeSend::getNoticeId,notices.get(i).getNoticeId());
                query.eq(SysNoticeSend::getUserId,userId);
                SysNoticeSend one = noticeSendService.getOne(query);
                if(null==one){
                    SysNoticeSend noticeSend = new SysNoticeSend();
                    noticeSend.setNoticeId(notices.get(i).getNoticeId());
                    noticeSend.setUserId(userId);
                    noticeSend.setReadFlag(Constants.NO_READ_FLAG);
                    noticeSendService.save(noticeSend);
                }
            }
        }
        // 2.查询用户未读的系统消息
        Page<SysNotice> anntMsgList = new Page<SysNotice>(0, pageSize);
        anntMsgList =iSysNoticeService.querySysNoticePageByUserId(anntMsgList,userId,"1");//通知公告消息
        Page<SysNotice> sysMsgList = new Page<SysNotice>(0, pageSize);
        sysMsgList = iSysNoticeService.querySysNoticePageByUserId(sysMsgList,userId,"2");//系统消息
        Page<SysNotice> todealMsgList = new Page<SysNotice>(0, pageSize);
        todealMsgList = iSysNoticeService.querySysNoticePageByUserId(todealMsgList,userId,"3");//待办消息
        Map<String,Object> sysMsgMap = new HashMap<String, Object>();
        sysMsgMap.put("sysMsgList", sysMsgList.getRecords());
        sysMsgMap.put("sysMsgTotal", sysMsgList.getTotal());
        sysMsgMap.put("anntMsgList", anntMsgList.getRecords());
        sysMsgMap.put("anntMsgTotal", anntMsgList.getTotal());
        sysMsgMap.put("todealMsgList", todealMsgList.getRecords());
        sysMsgMap.put("todealMsgTotal", todealMsgList.getTotal());
        return R.ok(sysMsgMap);
    }

}
